<script lang="ts" setup>
import { computed, ref, watch } from 'vue';

import { message, Modal } from 'ant-design-vue';

import { useVbenForm } from '#/adapter/form';
import {
  createResourceCategory,
  updateResourceCategory,
} from '#/api/resource-center';

import { useCategoryFormSchema } from '../data';

// Props
interface Props {
  visible: boolean;
  categoryData?: any;
}

const props = withDefaults(defineProps<Props>(), {
  visible: false,
  categoryData: null,
});

// Emits
const emit = defineEmits<{
  success: [];
  'update:visible': [value: boolean];
}>();

// 响应式数据
const submitLoading = ref(false);

// 表单相关
const [Form, formApi] = useVbenForm({
  schema: useCategoryFormSchema(),
  showDefaultActions: false,
});

// 计算属性
const modalTitle = computed(() => {
  return props.categoryData ? '编辑分类' : '新建分类';
});

// 监听数据变化
watch(
  () => props.categoryData,
  (newData) => {
    if (newData) {
      formApi.setValues(newData);
    } else {
      formApi.setValues({});
    }
  },
  { immediate: true },
);

// 方法
const handleCancel = () => {
  emit('update:visible', false);
  formApi.setValues({});
};

const handleSubmit = async () => {
  try {
    const { valid } = await formApi.validate();
    if (!valid) return;
    const values = await formApi.getValues();
    submitLoading.value = true;

    if (props.categoryData) {
      // 编辑
      await updateResourceCategory(props.categoryData.id, values);
      message.success('分类更新成功');
    } else {
      // 新建
      await createResourceCategory(values);
      message.success('分类创建成功');
    }

    emit('success');
  } catch (error) {
    console.error('Submit category error:', error);
    message.error('操作失败');
  } finally {
    submitLoading.value = false;
  }
};
</script>

<template>
  <Modal
    :open="visible"
    :title="modalTitle"
    width="800px"
    @cancel="handleCancel"
    @ok="handleSubmit"
    :confirm-loading="submitLoading"
  >
    <Form />
  </Modal>
</template>

<style lang="less" scoped>
:deep(.ant-form-item) {
  margin-bottom: 16px;
}
</style>
